package com.geek.javaCource.demo.masterslave.aop;

import com.geek.javaCource.demo.masterslave.datasource.DataSourceManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * Create by chenhd on 2021/9/21.
 */
@Aspect
@Component
@Slf4j
public class ReadOnlyAop {
    @Autowired
    @Qualifier(value = "master")
    DataSource masterDataSource;

    @Autowired
    @Qualifier(value = "slave")
    DataSource slaveDataSource;
    @Autowired
    DataSourceManager dataSourceManager;

    @Pointcut("@annotation(com.geek.javaCource.demo.masterslave.aop.ReadOnlyAnnotation)")
    public void readOnly() {
        //pointcut, do nothing
    }

    @Before("readOnly()")
    public void doBefore() {
        log.info("check to slave dataSource...");
        dataSourceManager.setCurrentDataSource(slaveDataSource);
    }

    @After("readOnly()")
    public void doAfter() {
        log.info("check to master dataSource...");
        dataSourceManager.setCurrentDataSource(masterDataSource);
    }
}
